package com.lis.scf.controller;


import com.lis.scf.common.dto.LoginDTO;
import com.lis.scf.common.dto.LoginResponseDTO;
import com.lis.scf.common.dto.ResponseDTO;
import com.lis.scf.common.dto.UserRegisterDTO;
import com.lis.scf.entity.Company;
import com.lis.scf.entity.User;
import com.lis.scf.repository.CompanyRepository;
import com.lis.scf.repository.RoleRepository;
import com.lis.scf.repository.UserRepository;
import com.lis.scf.service.AuthService;
import com.lis.scf.service.RegistrationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import javax.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.HashSet;
import java.util.Set;

/**
 * 认证控制器，处理登录、注册等请求
 */
@RestController
@RequestMapping("api/auth")
@RequiredArgsConstructor
@Api(tags = "认证管理", description = "用户登录、注册等认证相关接口")
public class AuthController {

    @Autowired
    private RegistrationService registrationService;

    @Autowired
    private AuthService authService;

    private final UserRepository userRepository;
    private final CompanyRepository companyRepository;
    private final RoleRepository roleRepository;
    private final PasswordEncoder passwordEncoder;

    @PostMapping("/test")
    public void test(){
        System.out.println("111");

    }
    /**
     * 用户注册
     */
    @PostMapping("/register1")
    public ResponseDTO<String> register1(@RequestBody UserRegisterDTO registerDTO) {
//
        // 检查用户名是否已存在
        if (userRepository.existsByUsername(registerDTO.getUsername())) {
            return ResponseDTO.fail("用户名已存在");
        }
        // 创建企业信息
        Company company = new Company();
        company.setCompanyName(registerDTO.getCompanyName());
        company.setUnifiedCreditCode(registerDTO.getUnifiedCreditCode());
        company.setCompanyType(registerDTO.getCompanyType());
        company = companyRepository.save(company);
        System.out.println("----创建用户-----");

        // 创建用户
        User user = new User();
        user.setUsername(registerDTO.getUsername());
        user.setPassword(passwordEncoder.encode(registerDTO.getPassword()));
        user.setMobileNumber(registerDTO.getMobileNumber());
        user.setRealName(registerDTO.getRealName());
        user.setCompany(company);
        user.setActive(true);

        // 分配默认角色
        Set<Long> roleIds = registerDTO.getRoleIds();
        if (roleIds != null && !roleIds.isEmpty()) {
            user.setRoles(new HashSet<>(roleRepository.findAllById(roleIds)));
        } else {
            // 如果没有指定角色，分配默认角色
            roleRepository.findByRoleName("ROLE_USER")
                    .ifPresent(role -> {
                        Set<com.lis.scf.entity.Role> roles = new HashSet<>();
                        roles.add(role);
                        user.setRoles(roles);
                    });
        }

        userRepository.save(user);
        return ResponseDTO.success("注册成功");
    }

    @PostMapping("/register")
    public ResponseDTO<String> register(@RequestBody UserRegisterDTO userRegisterDTO) {
        registrationService.register(userRegisterDTO);

        return ResponseDTO.success("注册成功");
    }

    /**
     * 发送验证码
     */
    @PostMapping("/send-code")
    public ResponseDTO<String> sendCode(@RequestBody String mobile) {
        // 实际项目中应该调用短信服务发送验证码
        // 这里简化处理，直接返回成功
        return ResponseDTO.success("验证码已发送至：" + mobile);
    }

    /**
     * 用户登录接口
     */
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户通过用户名和密码登录系统")
    @ApiResponses(value = {
            @ApiResponse(code = 200, message = "登录成功"),
            @ApiResponse(code = 401, message = "用户名或密码错误"),
            @ApiResponse(code = 403, message = "用户被禁用")
    })
    public ResponseDTO<LoginResponseDTO> login(
            @Valid @RequestBody LoginDTO loginDTO) {
        System.out.println(loginDTO);

        LoginResponseDTO loginResult = authService.login(loginDTO);
        return ResponseDTO.success( loginResult);
    }

    /***
     * 刷新令牌
     */
    @PostMapping("/token/refresh")
    public void refreshToken(@Valid @RequestBody String token) {


        System.out.println(token);
    }

}
